package def_config

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type RestReturnObj struct {
	Code   int         `json:"code"`
	Result bool        `json:"result"`
	Msg    string      `json:"msg"`
	Data   interface{} `json:"data"`
}

// 默认返回处理
func HandleReturn(reInfo any, retErr error, w http.ResponseWriter) {

	if retErr != nil {

		retInfo := RestReturnObj{
			Code:   500,
			Msg:    retErr.Error(),
			Data:   nil,
			Result: false,
		}
		//reInfo有值时为int类型的code
		if reInfo != nil {
			if code, ok := reInfo.(int); ok {
				retInfo.Code = code
			}
		}

		callReturnStr, err := json.Marshal(retInfo)
		if err != nil {
			panic(err)
		}
		fmt.Printf("%s\n", callReturnStr)
		w.Write([]byte(callReturnStr))

		return
	}

	if reInfo != nil { //有返回值
		retInfo := RestReturnObj{
			Code:   200,
			Msg:    "OK",
			Data:   reInfo,
			Result: true,
		}
		callReturnStr, err := json.Marshal(retInfo)
		if err != nil {
			panic(err)
		}
		w.Write([]byte(callReturnStr))
	} else {

		retInfo := RestReturnObj{
			Code:   200,
			Msg:    "OK",
			Data:   nil,
			Result: true,
		}
		callReturnStr, err := json.Marshal(retInfo)
		if err != nil {
			panic(err)
		}
		w.Write([]byte(callReturnStr))
	}

}
